package servlet;

import java.io.IOException;
import java.util.Date;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import session.AppointmentDao;
import session.CommentDao;
import utility.ReplaceString;
import entity.Comment;
import entity.User;

/**
 * Kontroler koji dodaje komentar za odgovarajuću utakmicu
 *
 * @author rigo & jung
 */
public class AddComment extends HttpServlet {

	private static final long serialVersionUID = 5626049682250850986L;

	final int MAX_SPACES = 10;
	
	@EJB
	protected CommentDao commentDao;
	@EJB
	protected AppointmentDao appointmentDao;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
			User user = (User)request.getSession().getAttribute("user");
			if(user==null) {
				getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
				return;
			}
			String appId=request.getParameter("appId");
			String comment = request.getParameter("comment");
			if(appId==null) {
				getServletContext().getRequestDispatcher("/main.jsp").forward(request, response);
				return;
			}
			if(comment==null || "".equalsIgnoreCase(comment.trim())) {
				getServletContext().getRequestDispatcher("/PrepareAppointmentView").forward(request, response);
				return;
			}				
			Comment comm= new Comment();
			comm.setText(ReplaceString.splitString(comment));
			comm.setAppointment(appointmentDao.findById(Integer.parseInt(appId)));
			comm.setUser(user);
			comm.setDate(new Date());
			comm.setDeleted(false);
			commentDao.persist(comm);
			getServletContext().getRequestDispatcher("/PrepareAppointmentView").forward(request, response);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
